package com.suneast.suneaststore.modules.store;

import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.RadioButton;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.suneast.suneaststore.R;
import com.suneast.suneaststore.modules.common.NavigationFragment;
import com.suneast.suneaststore.modules.store.adapter.StoreListAdapter;
import com.suneast.suneaststore.bean.homepage.StoreListBean;
import com.suneast.suneaststore.modules.homepage.event.StoreListResult;
import com.suneast.suneaststore.modules.common.Flag;
import com.suneast.suneaststore.ui.fragments.BaseFragment;
import com.tencent.map.geolocation.TencentLocation;
import com.tencent.map.geolocation.TencentLocationListener;
import com.tencent.map.geolocation.TencentLocationManager;
import com.tencent.map.geolocation.TencentLocationRequest;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.BindViews;
import butterknife.OnClick;

/**
 * Created by zestz on 2018/3/24.
 */

public class StoreListFragment extends BaseFragment implements StoreListAdapter.OnClickListener, TencentLocationListener {
    private final static String TAG = StoreListFragment.class.getSimpleName();
    private List<StoreListBean.Store> tempList = new ArrayList<>();
    private StoreListAdapter hallAdapter;

    private int filterChoice = 0;
    private int typeChoice = 0;
    private int pageIndex = 1;

    private float curLatitude = -1, curLongitude = -1;

    private TencentLocationManager locationManager;
    private TencentLocationRequest request;

    @Override
    public @LayoutRes
    int setLayout() {
        return R.layout.fragment_store_list;
    }

    @BindViews({R.id.filter_default, R.id.filter_positive_feedback, R.id.filter_sales_priority})
    RadioButton[] rbPreferenceFilter;
    @BindViews({R.id.filter_center, R.id.filter_shop})
    RadioButton[] rbShopFilter;
    @BindView(R.id.rv_store)
    RecyclerView rvStore;
    @BindView(R.id.srl_layout)
    SmartRefreshLayout srlLayout;
    @BindView(R.id.srlHeader)
    ClassicsHeader srlHeader;
    @BindView(R.id.srlFooter)
    ClassicsFooter srlFooter;

    @OnClick(R.id.ib_return_back)
    void onBackPressed() {
        pop();
    }

    @OnClick({R.id.filter_default, R.id.filter_positive_feedback, R.id.filter_sales_priority})
    void onFilterOneClick(View view) {
        switch (view.getId()) {
            case R.id.filter_positive_feedback:
                filterChoice = 1;
                break;
            case R.id.filter_sales_priority:
                filterChoice = 2;
                break;
            case R.id.filter_default:
                filterChoice = 0;
                break;
        }
        android.util.Log.d(TAG, "filterChoice: " + filterChoice);
        requestList();
    }

    @OnClick({R.id.filter_center, R.id.filter_shop})
    void onFilterTwoClick(View view) {
        switch (view.getId()) {
            case R.id.filter_center:
                typeChoice = 0;
                break;
            case R.id.filter_shop:
                typeChoice = 1;
                break;
        }
        android.util.Log.d(TAG, "typeChoice: " + typeChoice);
        requestList();
    }

    private void requestList() {
        tempList.clear();
        StoreHandler.requestStoreList(typeChoice, filterChoice, curLatitude, curLongitude, pageIndex = 1);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        locationManager = TencentLocationManager.getInstance(getContext());
        locationManager.removeUpdates(null);
        locationManager.setCoordinateType(TencentLocationManager.COORDINATE_TYPE_GCJ02);
        request = TencentLocationRequest.create();
        request.setInterval(3000);
        locationManager.requestLocationUpdates(request, this);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            locationManager.removeUpdates(this);
        } else {
            locationManager.removeUpdates(null);
            locationManager.requestLocationUpdates(request, this);
        }
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View rootView) {
        rvStore.setLayoutManager(new LinearLayoutManager(getContext()));
        hallAdapter = new StoreListAdapter();
        hallAdapter.setOnclickListener(this);
        rvStore.setAdapter(hallAdapter);
        srlLayout.setEnableLoadMoreWhenContentNotFull(false);

//        StoreListBean bean = JSON.parseObject(JSON.parseObject(Test.testJson).getJSONObject("data").toJSONString(), StoreListBean.class);
//        android.util.Log.e(TAG, "list: "+bean.getGoodsShowList());
//        tempList.addAll(bean.getGoodsShowList());
//        hallAdapter.setGoodsShowList(tempList);
        srlLayout.setEnableLoadMoreWhenContentNotFull(false);
        srlLayout.setOnRefreshListener(refreshLayout -> requestList());
        srlLayout.setOnLoadMoreListener(refreshLayout -> {
            srlFooter.setNoMoreData(false);
            StoreHandler.requestStoreList(typeChoice, filterChoice, curLatitude, curLongitude, pageIndex);
        });
        EventBus.getDefault().register(this);
        rbPreferenceFilter[0].setChecked(true);
        rbShopFilter[0].performClick();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onStoreListResult(StoreListResult result) {
        int type = result.getType();
        int filter = result.getFilter();
        if (typeChoice == type && filterChoice == filter) {
            if (result.getValue() == Flag.Result.SUCCEED) {
                if (result.getBean() != null) {
                    tempList.addAll(result.getBean().getList());
                    srlLayout.postDelayed(pageIndex == 1 ?
                            () -> srlLayout.finishRefresh(true) : () -> srlLayout.finishLoadMore(true), 500);
                    hallAdapter.setList(tempList);
                    pageIndex++;
                } else if (pageIndex == 1) {
                    // 无数据 (走到这一般是出故障了)
                    srlLayout.postDelayed(() -> srlLayout.finishRefresh(true), 500);
                } else {
                    // 已全部加载 (走到这一般是出故障了)
                    srlLayout.postDelayed(() -> srlLayout.finishLoadMore(true), 500);
                }
            } else {
                boolean flag = "没有数据".equals(result.getMsg());
                boolean pageFlag = pageIndex == 1;
                if (flag) { // 如是没有数据,page==1说明真的没有,否则就是已经加载到底了
                    if (!pageFlag) {
                        srlFooter.setNoMoreData(true);
                    }
                } else {
                    hallAdapter.setList(null);
                }
                srlLayout.postDelayed(pageFlag ?
                        () -> srlLayout.finishRefresh(flag) : () -> srlLayout.finishLoadMore(flag), 500);
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        locationManager.removeUpdates(this);
    }

    @Override
    public void onItem(int position) {
        if (tempList.size() > position) {
            start(new StoreFragment().withId(tempList.get(position).getId()));
        }
    }

    @Override
    public void onNavigate(int position) {
        if (tempList.size() > position) {
            StoreListBean.Store store = tempList.get(position);
            start(new NavigationFragment().navigate(store.getLng(), store.getLat(), store.getMerchname(), store.getAddress()));
//            start(new NavigationFragment().search(store.getLng(), store.getLat(), store.getMerchname(), 1000));
        }
    }

    @Override
    public void onLocationChanged(TencentLocation location, int error, String reason) {
        if (error == TencentLocation.ERROR_OK) {
            curLatitude = (float) location.getLatitude();
            curLongitude = (float) location.getLongitude();
            android.util.Log.e(TAG, "lat: " + curLatitude);
            android.util.Log.e(TAG, "lng: " + curLongitude);
            android.util.Log.e(TAG, "name: " + location.getName());
        } else {
            android.util.Log.e(TAG, "locate err: " + reason);
        }
    }

    @Override
    public void onStatusUpdate(String s, int i, String s1) {
        // i don't care
    }
}
